package com.ldfile.server.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class QRCodeUtil {

    public static void main(String[] args) throws FileNotFoundException {
        System.out.println(System.currentTimeMillis());
        QRCodeUtil.zxingCodeCreate("teststddddddddddddddddddddddddddddddddddddddsssssssssssssssssssssss",
                "", 200, 200,
                new FileOutputStream("C:\\Users\\xiaoyelj\\Desktop\\c.jpg"), "jpg", 0, null);
        System.out.println(System.currentTimeMillis());
    }

    /**
     * 生成二维码并写入out
     *
     * @param content
     * @param title
     * @param width
     * @param height
     * @param out
     * @param mode
     * @param level
     * @param in
     * @throws IOException
     */
    public static void zxingCodeCreate(String content, String title, int width,
                                       int height, OutputStream out, String mode, int level, InputStream in) {

        try {
            ImageIO.write(zxingCodeCreate(content, title, width, height, mode, level, in), mode, out);
        } catch (IOException | WriterException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param content
     * @param title
     * @param width
     * @param height
     * @param mode
     * @param level
     * @param in
     * @return
     */
    public static BufferedImage zxingCodeCreate(String content, String title, int width,
                                                int height, String mode, int level, InputStream in) throws WriterException, IOException {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.forBits(level));// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
        if (StringUtils.isEmpty(title))
            hints.put(EncodeHintType.MARGIN, 0);
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
        BitMatrix bm = multiFormatWriter.encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);

        // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bm.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (in != null) {
            // 构建绘图对象
            Graphics2D g = image.createGraphics();
            // 读取Logo图片
            BufferedImage logo = ImageIO.read(in);
            // 开始绘制logo图片
            g.drawImage(logo.getScaledInstance(width * 4 / 15, height * 4 / 15, Image.SCALE_SMOOTH), width * 11 / 30, height * 11 / 30, width * 4 / 15,
                    height * 4 / 15, null);
            g.dispose();
            logo.flush();
        }
        // 新的图片，把带logo的二维码下面加上文字
        BufferedImage outImage = new BufferedImage(image.getWidth(), image.getHeight(),
                BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D outg = outImage.createGraphics();
        outg.setColor(Color.white);
        //背景填充为白色
        outg.fillRect(0, 0, outImage.getWidth(), outImage.getHeight());
        // 画二维码到新的面板
        outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
        // 画文字到新的面板
        if (!StringUtils.isEmpty(title)) {
            outg.setColor(Color.blue);
            outg.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
            int strWidth = outg.getFontMetrics().stringWidth(title);
            outg.drawString(title, (outImage.getWidth() - strWidth) / 2, image.getHeight()); // 画文字
        }
        return image;
    }
}
